//代码生成时,文件路径: e:/download/quickbundle-securityweb/src/main/java/orgauth/rmfunctionnode/web/RmFunctionNodeAction.java
//代码生成时,系统时间: 2010-11-27 22:08:40
//代码生成时,操作系统用户: Administrator

/*
 * 系统名称:单表模板 --> quickbundle-securityweb
 * 
 * 文件名称: org.quickbundle.orgauth.rmfunctionnode.web --> RmFunctionNodeAction.java
 * 
 * 功能描述:
 * 
 * 版本历史: 2010-11-27 22:08:40 创建1.0.0版 (白小勇)
 *  
 */

package org.quickbundle.orgauth.rmfunctionnode.web;

import java.io.FilenameFilter;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.quickbundle.base.beans.factory.RmBeanFactory;
import org.quickbundle.base.web.page.RmPageVo;
import org.quickbundle.orgauth.rmfunctionnode.service.IRmFunctionNodeService;
import org.quickbundle.orgauth.rmfunctionnode.util.IRmFunctionNodeConstants;
import org.quickbundle.orgauth.rmfunctionnode.vo.RmFunctionNodeVo;
import org.quickbundle.project.IGlobalConstants;
import org.quickbundle.project.RmGlobalReference;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.cache.RmSqlCountCache;
import org.quickbundle.third.struts.RmActionHelper;
import org.quickbundle.third.struts.actions.RmDispatchAction;
import org.quickbundle.tools.helper.RmJspHelper;
import org.quickbundle.tools.helper.RmPopulateHelper;
import org.quickbundle.tools.helper.RmSqlHelper;
import org.quickbundle.tools.helper.RmStringHelper;
import org.quickbundle.tools.helper.RmVoHelper;

import com.alibaba.fastjson.JSON;
import com.dfhc.ISystemConstant;
import com.dfhc.pub.service.PickMenuLinkInPageService;
import com.dfhc.util.CommentFileFilter;
import com.dfhc.util.FileOperateHelper;
import com.dfhc.util.HttpClientUtil;
import com.dfhc.util.StringHelper;

/**
 * 功能、用途、现存BUG:
 * 
 * @author 白小勇
 * @version 1.0.0
 * @see 需要参见的其它类
 * @since 1.0.0
 */

public class RmFunctionNodeAction extends RmDispatchAction implements IRmFunctionNodeConstants {
	/**
	 * 提取菜单servername，使用localhost以避免经过代理后，后台无法访问前台代理情况
	 */
	private static final String PICK_MENU_SERVER_NAME="localhost";
    /**
     * 得到Service对象
     * 
     * @return Service对象
     */
    public IRmFunctionNodeService getService() {
        return (IRmFunctionNodeService) RmBeanFactory.getBean(SERVICE_KEY);  //得到Service对象,受事务控制
    }
    /**
     * 得到提取链接菜单服务
     * 
     * @return Service对象
     */
    public PickMenuLinkInPageService getPickMenuLinkService() {
        return (PickMenuLinkInPageService) RmBeanFactory.getBean("pickMenuLinkInPageService");  //得到Service对象,受事务控制
    }

    /**
     * 从页面表单获取信息注入vo，并插入单条记录
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response 
     * @return
     * @throws Exception
     */
    public ActionForward insert(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //dealWithUrl(request);
		String[] names =request.getParameterValues("names");
//    	 
//    	RmFunctionNodeVo vo = new RmFunctionNodeVo();
//        RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
//        RmVoHelper.markCreateStamp(request,vo);  //打创建时间,IP戳
//        vo.setIs_leaf("1"); //默认子节点·
//        String id = getService().insert(vo);  //插入单条记录
//        request.setAttribute(IGlobalConstants.INSERT_FORM_ID, id);  //新增记录的id放入request属性
//        
//        if(names!=null){
//	        for (int i = 0; i < names.length; i++) {
//				int val=100+i;
//				String total_code = request.getParameter("total_code");
//				total_code+=val;
//				vo = new RmFunctionNodeVo();
//				vo.setNode_type("2");
//				vo.setFunction_property("3");
//				vo.setName(names[i]);
//				vo.setEnable_status("1");
//				vo.setTotal_code(total_code);
//				vo.setFuncnode_authorize_type("1");
//				vo.setData_value(names[i]);
//				vo.setIs_leaf("1");
//				vo.setUsable_status("1");
//				RmVoHelper.markCreateStamp(request,vo); 
//				id = getService().insert(vo);  //插入单条记录
//		        request.setAttribute(IGlobalConstants.INSERT_FORM_ID, id);  //新增记录的id放入request属性
//			}
//        }
        //插入本节点及节点对应页面的页内链接(如果有的话)
        getService().insertSelfAndLinkInPage(names,request);
        return RmActionHelper.getForwardInstance("/orgauth/tree/functionNode.jsp");
    }
    /**
     * 新增菜单时，从页面提取页内链接 
     */
    public ActionForward dealWithUrl(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String menuUrl = request.getParameter("menuUrl");

		 String regEx = RmGlobalReference.get(ISystemConstant.REGULAR_EX, "01");
	
		menuUrl=request.getScheme()+"://"+PICK_MENU_SERVER_NAME+":"+getWebServerPort()+request.getContextPath()+menuUrl;
		
		HashMap<String, String> hashMap = new HashMap<>();
		hashMap.put("Host",PICK_MENU_SERVER_NAME+":"+getWebServerPort() );
		hashMap.put("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
		hashMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		hashMap.put("Accept-Encoding", "gzip, deflate");
		hashMap.put("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
		hashMap.put("Connection", "keep-alive");
		hashMap.put("Referer", request.getScheme()+"://"+PICK_MENU_SERVER_NAME+":"+getWebServerPort()+request.getContextPath());
		hashMap.put("Cookie", "JSESSIONID="+request.getSession().getId());
		String htmlPage=HttpClientUtil.get(menuUrl,hashMap);
	
		
	    Pattern pattern = Pattern.compile(regEx);
	    Matcher matcher = pattern.matcher(htmlPage.toString());
	    ArrayList<String> arrayList = new ArrayList<>();
	   	    
	    while( matcher.find()){
	    	String oldlink="";
	    	for(int i=1;i<=matcher.groupCount();i++){
	    		if(matcher.group(i)!=null){
	    			oldlink=matcher.group(i);
	    			
	    			break;
	    		}
	    	}
	    	String contextPath = request.getContextPath();

	    	String link = StringHelper.replaceAll(oldlink, contextPath, "").toString();

	    	 link = link.replace("+", "");
	    	  link = link.replace("\"", "");
	    	  link = link.replace(" ", "");
	    	
	    	arrayList.add(link);
	    }
	    
	   response.setContentType("text/text;charset=utf-8");
	   response.setHeader("cache-control", "no-cache");
	    OutputStream stream = response.getOutputStream();
	    String data = JSON.toJSONString(arrayList);
	    
	    stream.write(data.getBytes("UTF-8"));
		return null;
	}

	/**
     * 从页面的表单获取单条记录id，并删除单条记录
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response 
     * @return
     * @throws Exception
     */
    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	if(RmStringHelper.checkNotEmpty(request.getParameter("total_code"))){
    		getService().deleteFunctionNode(request.getParameter(REQUEST_ID),request.getParameter("total_code"));
    	}
        return RmActionHelper.getForwardInstance("/orgauth/tree/functionNode.jsp");
    }

    /**
     * 从页面的表单获取多条记录id，并删除多条记录
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response 
     * @return
     * @throws Exception
     */
    public ActionForward deleteMulti(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] id = RmJspHelper.getArrayFromRequest(request, REQUEST_IDS);  //从request获取多条记录id
        int deleteCount = 0;  //定义成功删除的记录数
        if (id != null && id.length != 0) {
            deleteCount = getService().delete(id);  //删除多条记录
        }
        request.setAttribute(EXECUTE_ROW_COUNT, deleteCount);  //sql影响的行数放入request属性
        return mapping.findForward(FORWARD_TO_QUERY_ALL);
    }

    /**
     * 从页面的表单获取单条记录id，查出这条记录的值，并跳转到修改页面
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response 
     * @return
     * @throws Exception
     */
    public ActionForward find(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        detail(mapping, form, request, response);
        return mapping.findForward(FORWARD_UPDATE_PAGE);
    }

    /**
     * 从页面表单获取信息注入vo，并修改单条记录
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response 
     * @return
     * @throws Exception
     */
    public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
	   
	    String[] names =request.getParameterValues("names");
	    String total_code = request.getParameter("total_code");	
	    getService().deleteByTotalCode(total_code+"___",ISystemConstant.DICTIONARY_FUNCTION_PROPERTY_3);
	    
    	RmFunctionNodeVo vo = new RmFunctionNodeVo();
        RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
        RmVoHelper.markModifyStamp(request,vo);  //打修改时间,IP戳
        int count = getService().update(vo);  //更新单条记录
        request.setAttribute(EXECUTE_ROW_COUNT, count);  //sql影响的行数放入request属性*/
	    /*RmFunctionNodeVo vo = new RmFunctionNodeVo();
        RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
        RmVoHelper.markCreateStamp(request,vo);  //打创建时间,IP戳
        vo.setIs_leaf("1"); //默认子节点·
        String id = getService().insert(vo);  //插入单条记录
        request.setAttribute(IGlobalConstants.INSERT_FORM_ID, id);  //新增记录的id放入request属性
*/        
        if(names!=null && names.length>0){
	        for (int i = 0,val=100; i < names.length; i++,val++) {
				val=getNewTotalCode(total_code, val);				
				vo = new RmFunctionNodeVo();
				vo.setNode_type("2");
				vo.setFunction_property("3");
				vo.setName(names[i]);
				vo.setEnable_status("1");
				vo.setTotal_code(total_code+val);
				vo.setFuncnode_authorize_type("1");
				vo.setData_value(names[i]);
				vo.setIs_leaf("1");
				vo.setUsable_status("1");
				RmVoHelper.markCreateStamp(request,vo); 
				String id = getService().insert(vo);  //插入单条记录
		        request.setAttribute(IGlobalConstants.INSERT_FORM_ID, id);  //新增记录的id放入request属性
			}
        }
        return RmActionHelper.getForwardInstance("/orgauth/tree/functionNode.jsp");
    }
	/**
	 * 获取新的菜单码
	 * @param total_code
	 * @param val
	 * @return
	 */
	private int getNewTotalCode(String total_code, int val) {
		
		String sql="select count(*) from rm_function_node where total_code='%s'";
		while(true){			
			if(RmProjectHelper.getCommonServiceInstance().doQueryForInt(String.format(sql, total_code+val))==0){
				break;
			}
			val++;
		}
		return val;
	}
    /**
     * 简单查询，分页显示，支持表单回写
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response 
     * @return
     * @throws Exception
     */
    public ActionForward simpleQuery(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        IRmFunctionNodeService service = getService();
        String queryCondition = getQueryCondition(request);  //从request中获得查询条件
        RmPageVo pageVo = RmJspHelper.transctPageVo(request, getCount(queryCondition));
        String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息
        List<RmFunctionNodeVo> beans = service.queryByCondition(queryCondition, orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
        //如果采用下边这句，就是不带翻页的，同时需要删掉list页面的page.jsp相关语句
        //beans = service.queryByCondition(queryCondition, orderStr);  //查询全部,带排序
        RmJspHelper.saveOrderStr(orderStr, request);  //保存排序信息
        request.setAttribute(REQUEST_QUERY_CONDITION, queryCondition);
        request.setAttribute(REQUEST_BEANS, beans);  //把结果集放入request
        request.setAttribute(REQUEST_WRITE_BACK_FORM_VALUES, RmVoHelper.getMapFromRequest((HttpServletRequest) request));  //回写表单
        return mapping.findForward(FORWARD_LIST_PAGE);
    }

    /**
     * 查询全部记录，分页显示，支持页面上触发的后台排序
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response 
     * @return
     * @throws Exception
     */
    public ActionForward queryAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setAttribute(REQUEST_QUERY_CONDITION, "");
        simpleQuery(mapping, form, request, response);
        return mapping.findForward(FORWARD_LIST_PAGE);
    }

    /**
     * 从页面的表单获取单条记录id，并察看这条记录的详细信息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response 
     * @return
     * @throws Exception
     */
    public ActionForward detail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        RmFunctionNodeVo bean = getService().find(request.getParameter(REQUEST_ID));  //通过id获取vo
        String total_code = bean.getTotal_code();
        List<RmFunctionNodeVo> beanList = getService().findByTotalCode(total_code+"___",ISystemConstant.DICTIONARY_FUNCTION_PROPERTY_3);
        request.setAttribute(REQUEST_BEAN, bean);  //把vo放入request
        request.setAttribute(REQUEST_BEAN_LIST, beanList);  //把选中的业内连接放入request
        request.setAttribute("IS_UPDATE", "TRUE");
        //获取jsp根目录
        String jspRootPath = FileOperateHelper.getProjectPath(request);
        jspRootPath = jspRootPath+ ISystemConstant.JSP_RELA_ROOT_PATH;
        
        request.setAttribute("jspRootPath", jspRootPath);        
//        String string = RmGlobalReference.get("dictionaryType", "dictionaryKey");
        String regEx = RmGlobalReference.get(ISystemConstant.REGULAR_EX, "01");
        /*String regEx="form.action=\"(.+?);" ;*/
        String menuUrl = request.getParameter("data_value");
        ArrayList<String> arrayList = new ArrayList<>();
        if(!StringHelper.isEmpty(menuUrl)){
			menuUrl=request.getScheme()+"://"+PICK_MENU_SERVER_NAME+":"+getWebServerPort()+request.getContextPath()+menuUrl;
			
			HashMap<String, String> hashMap = new HashMap<>();
			hashMap.put("Host",PICK_MENU_SERVER_NAME+":"+getWebServerPort() );
			hashMap.put("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
			hashMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			hashMap.put("Accept-Encoding", "gzip, deflate");
			hashMap.put("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			hashMap.put("Connection", "keep-alive");
			hashMap.put("Referer", request.getScheme()+"://"+PICK_MENU_SERVER_NAME+":"+getWebServerPort()+request.getContextPath());
			hashMap.put("Cookie", "JSESSIONID="+request.getSession().getId());
			String htmlPage=HttpClientUtil.get(menuUrl,hashMap);
			
		    Pattern pattern = Pattern.compile(regEx);
		    Matcher matcher = pattern.matcher(htmlPage.toString());
		   	    
		    String contextPath = request.getContextPath();
		    while( matcher.find()){
		    	String oldlink="";
		    	for(int i=1;i<=matcher.groupCount();i++){
		    		oldlink=matcher.group(i);
		    		if(!StringHelper.isEmpty(oldlink)){
		    			break;
		    		}
		    	}
		    	if(!StringHelper.isEmpty(oldlink) && StringHelper.findStrNum(oldlink, "/")>0){
			    	String	link= oldlink.replace(contextPath, "");
			    	link = link.replace("+", "");
			    	link = link.replace("\"", "");
			    	link = link.replace(" ", "");
			    	arrayList.add(link);
		    	}
		    }
		    Iterator<String> iterator = arrayList.iterator();
		    while(iterator.hasNext()){
		    	String next = iterator.next();
		    	for(int i=0;i<beanList.size();i++){
		    		if(beanList.get(i).getData_value().equals(next)){
		    			iterator.remove();
		    			break;
		    		}
		    	}
		    }
        }
	    request.setAttribute("unchecked", arrayList); 
	    
        if(RM_YES.equals(request.getParameter(REQUEST_IS_READ_ONLY))) {
            request.setAttribute(REQUEST_IS_READ_ONLY, request.getParameter(REQUEST_IS_READ_ONLY));
        }
        return mapping.findForward(FORWARD_DETAIL_PAGE);
    }

	
    
    /**
     * 功能: 从request中获得查询条件
     *
     * @param request
     * @return
     */
    protected String getQueryCondition(HttpServletRequest request) {
        String queryCondition = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            queryCondition = request.getAttribute(REQUEST_QUERY_CONDITION).toString();
        } else {
			List<String> lQuery = new ArrayList<String>();
			
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".node_type", request.getParameter("node_type"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".function_property", request.getParameter("function_property"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".name", request.getParameter("name"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".enable_status", request.getParameter("enable_status"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".total_code", request.getParameter("total_code"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".order_code", request.getParameter("order_code"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".funcnode_authorize_type", request.getParameter("funcnode_authorize_type"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".description", request.getParameter("description"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".data_value", request.getParameter("data_value"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".pattern_value", request.getParameter("pattern_value"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".is_leaf", request.getParameter("is_leaf"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".icon", request.getParameter("icon"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".help_name", request.getParameter("help_name"), RmSqlHelper.TYPE_CHAR_LIKE));
				
			queryCondition = RmSqlHelper.appendQueryStr(lQuery.toArray(new String[0]));
        }
        return queryCondition;
    }
    
    /**
     * 得到缓存中查询条件对应的count(*)记录数，如返回-1则执行查询
     * 
     * @param queryCondition
     * @return
     */
    protected int getCount(String queryCondition) {
    	int count = RmSqlCountCache.getCount(TABLE_NAME, queryCondition);
    	if(count < 0) {
    		count = getService().getRecordCount(queryCondition);
    		RmSqlCountCache.putCount(TABLE_NAME, queryCondition, count);
    	}
    	return count;
    }
    /**
     * 获取webserver端口
     * @return
     */
    private String getWebServerPort(){
    	return RmGlobalReference.get(ISystemConstant.DICTIONARY_WEBSERVER_CONFIG, ISystemConstant.DICTIONARY_WEBSERVER_PORT);
    }
    /**
     * 从jsp目录提取链接 
     */
    public ActionForward importFunctionLink(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String jspPath = request.getParameter("jspPath");
    	String totalCode = request.getParameter("total_Code");
    	response.setContentType("text/text;charset=utf-8");
 	    response.setHeader("cache-control", "no-cache");
 	    OutputStream stream = response.getOutputStream();
    	
 	   if(StringHelper.isEmpty(totalCode)||StringHelper.isEmpty(jspPath)){
 		 stream.write("缺少参数".getBytes("UTF-8"));
 		 return null;
 	   }
	   List<String> arrayList = new ArrayList<>();
	   
	   FilenameFilter fileFilter = new CommentFileFilter(".*.jsp");
	   List<String> files = FileOperateHelper.searchFile(jspPath, fileFilter);
	   List<String> menuCodeList = new ArrayList<String>();
	   menuCodeList.add(totalCode);
	   getPickMenuLinkService().init();
	   getPickMenuLinkService().clearMenuList();
	   //循环提取文件
	   if(files!=null){
		   for(String fileName:files){			   
			   getPickMenuLinkService().pickLinkFromFile(fileName, menuCodeList);   
		   }
	   }
	   
	   List<String> menuLinks = getPickMenuLinkService().getMenuLinkList();
	   
	   //提出已经存在的链接,并加工
	   for(String menuLink:menuLinks){
		   menuLink = getPickMenuLinkService().fixMenuLink(menuLink);
		   arrayList.add(menuLink);
				   
	   }
	   String data = JSON.toJSONString(arrayList);
	    
	   stream.write(data.getBytes("UTF-8"));
	   return null;
	}    
}